package fr.ssd.sdl.parser;

import java.util.Set;


public class ParserImpl implements Parser{
	
	@Override
	public void parseStatement(String sqlStatement, Set<Parameter> keys) throws ParserException {
		int idx = 0;
		while(idx < sqlStatement.lastIndexOf("${")){
			Parameter p = findNextParameter(idx, sqlStatement);
			idx = p.idxEnd;
			keys.add(p);
		}
	}

	@Override
	public String replaceKeys(String sqlStatement, Set<Parameter> resolvedKeys) throws ParserException {
		int idx = 0;
		Parameter p;
		String resolvedSqlStatement = sqlStatement;
		while(idx <= sqlStatement.lastIndexOf("${")){
			p = findNextParameter(idx, sqlStatement);
			idx = p.idxEnd;
			for(Parameter param : resolvedKeys){
				if(param.equals(p)){
					resolvedSqlStatement = resolvedSqlStatement.replace(param.getAttName().subSequence(0, param.getAttName().length()), param.resolvedKey.subSequence(0, param.resolvedKey.length()));
				}
			}
		}
		return resolvedSqlStatement;
	}
	
	protected Parameter findNextParameter(int index, String statement) throws ParserException{
		Parameter p = new Parameter();
		int paramBegin = statement.indexOf("${", index);
		int paramEnd = -1;
		if (paramBegin > 0){
			paramEnd = statement.indexOf("}", paramBegin);
			if(paramEnd > 0){
				String s = statement.substring(paramBegin+2, paramEnd);
				String[] k = s.split("\\.");
				p.table  = k[0];
				p.column = k[1];
				p.localKey = k[2];
			}else{
				throw new ParserException("find \"${\" without corresponding \"}\"", null);
			}
		}
		p.idxBegin = paramBegin;
		p.idxEnd = paramEnd;
		return p;
	}

}
